//
//  LHNetWorkRequestManager.m
//  EPA
//
//  Created by 卢浩 on 16/4/15.
//  Copyright © 2016年 卢浩. All rights reserved.
//

#import "LHNetWorkRequestManager.h"

@implementation LHNetWorkRequestManager

//请求方法
+ (void)requestUrl:(NSURL *)url Methed:(URLRequestMethed)methed Params:(NSDictionary *)param Result:(ResultBlock)resultBlock{
    
    //url参数允许输入字符串,容错
    //空的可变字符串
    NSMutableString *urlStr = [NSMutableString string];
    if ([url isKindOfClass:[NSURL class]]) {
        //拼接url
        [urlStr appendString:url.absoluteString];
    }else if ([url isKindOfClass:[NSString class]]){
        [urlStr appendString:(NSString *)url];
    }
    if (urlStr.length == 0) {
        NSError *error = [NSError errorWithDomain:@"EPA" code:251 userInfo:@{@"reason":@"您输入的网址不正确"}];
        resultBlock(nil,nil,error);
        return;
    }
    
    LHNetWorkRequestManager *manager = [LHNetWorkRequestManager new];
    //把参数字典转为字符串
    NSString *paraStr = [manager strFromDict:param];
    
    //判断请求方式
    switch (methed) {
        case GET:{
            if (paraStr.length > 0) {
                [urlStr appendFormat:@"?%@",paraStr];
            }
            [manager getRequestWithURL:[NSURL URLWithString:urlStr] resultBlock:resultBlock];
            break;
        }
        case  POST:{
            [manager postRequestWithURL:[NSURL URLWithString:urlStr] ParaStr:paraStr resultBlock:resultBlock];
            break;
        }
        default:
            break;
    }
}

//GET网络请求
- (void)getRequestWithURL:(NSURL *)url resultBlock:(ResultBlock)block{
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:block];
    [dataTask resume];
}

//POST网络请求
- (void)postRequestWithURL:(NSURL *)url ParaStr:(NSString *)paraStr resultBlock:(ResultBlock)block{
    //创建可变请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置POST
    request.HTTPMethod = @"POST";
    //设置请求体
    request.HTTPBody = [paraStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:block];
    [dataTask resume];
}

- (NSString *)strFromDict:(NSDictionary *)dict{
    return [LHNetWorkRequestManager strWithDict:dict];
}

//把参数字典转为字符串
+ (NSString *)strWithDict:(NSDictionary *)dict{
    //空字符串
    NSMutableString *paraStr = [NSMutableString string];
    //空数组
    NSMutableArray *array = [NSMutableArray new];
    for (NSString *key in dict.allKeys) {
        NSString *str = [NSString stringWithFormat:@"%@=%@",key,dict[key]];
        [array addObject:str];
    }
    [paraStr appendString:[array componentsJoinedByString:@"&"]];
//    NSLog(@"%@",paraStr);
    return paraStr;
}

@end
